//
//  RHEquipmentRepairVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2023/8/16.
//

#import "RHEquipmentRepairVC.h"
#import "RHAddDeviceCell.h"
#import "CDZQRScanViewController.h"
#import "RHNavigationController.h"
#import "ChoiceDeviceVC.h"
#import "RHDeviceModel.h"

@interface RHEquipmentRepairVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) NSArray *dataArr;

@property (nonatomic ,strong) UIView *headerView;

@property (nonatomic ,strong) UIView *footerView;

@property(nonatomic ,strong) QMUIButton *deleteBtnB;

@property(nonatomic, strong) QMUITextView *textView;

@property(nonatomic ,strong) UIImageView *plantImg;

@property(nonatomic ,copy) NSString *uploadImgUrl;

@property(nonatomic ,strong) NSMutableDictionary *para;

@property(nonatomic ,copy) NSString *superUser;
@end


@implementation RHEquipmentRepairVC
-(NSMutableDictionary *)para
{
    if(!_para){
        _para = [NSMutableDictionary dictionary];
    }
    return _para;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = CFTabViewBgColor;
    self.navigationItem.title = @"设备维修".rh_localized;
    [self setupUI];
    [self getSuperUserInfo];
}

-(void)setDevModel:(RHDeviceModel *)devModel
{
    _devModel = devModel;
    self.dataArr = @[ValidNullData(devModel.deviceName),ValidNullData(devModel.deviceId),ValidNullData(self.superUser)];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
    });
    
}


- (void)setupUI{
    if(!self.devModel){
        self.dataArr = @[@"",@"",@""];
    }
    QMUIButton *createBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [createBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [createBtn setTitle:@"提交".rh_localized forState:UIControlStateNormal];
    [createBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [createBtn.layer setCornerRadius:8];
    [createBtn setBackgroundColor:CMainColorGreen];
    [self.view addSubview:createBtn];
    [createBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.height.mas_equalTo(50);
        make.bottom.mas_offset(kSafe_bottom>0?-kSafe_bottom:-15);
    }];
    [createBtn addTarget:self action:@selector(checkInfo) forControlEvents:UIControlEventTouchUpInside];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setBackgroundColor:UIColor.clearColor];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView registerClass:[RHAddDeviceCell class] forCellReuseIdentifier:@"RHAddDeviceCell"];
    _tableView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"nodata_icon_1" titleStr:@"没有数据".rh_localized detailStr:@""];
    [self.view addSubview:_tableView];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_offset(0);
        make.bottom.equalTo(createBtn.mas_top).offset(-15);
    }];
    
}


- (UIView *)footerView{
    if(!_footerView){
        _footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,380)];
        [_footerView setBackgroundColor:UIColor.clearColor];
        
        UIView *bgView =  [[UIView alloc] initWithFrame:CGRectMake(15, 15, SCREEN_WIDTH-30,300)];
        [bgView setBackgroundColor:UIColor.whiteColor];
        [bgView rounded:8 width:1 color:kBorderColor];
        [_footerView addSubview:bgView];
        
        
        QMUILabel *lab = [[QMUILabel alloc] init];
        [lab setText:@"问题描述".rh_localized];
        [lab setTextAlignment:NSTextAlignmentLeft];
        [lab setFont:[UIFont systemFontOfSize:14]];
        [lab setTextColor:kCOLOR_HEX(@"3F4443")];
        [bgView addSubview:lab];
        
        QMUITextView *textView = [[QMUITextView alloc]init];
        textView.placeholder = @"请输入问题描述(10-100个字符)".rh_localized;
        textView.backgroundColor = [UIColor colorWithHexString:@"F4F4F4"];
        textView.placeholderColor = [UIColor colorWithHexString:@"BBBBBB"];
        textView.layer.cornerRadius = 8;
        textView.layer.masksToBounds = YES;
        textView.maximumTextLength = 100;
        [bgView addSubview:textView];
        self.textView = textView;
        
        
        QMUIButton *addPicBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
        [addPicBtn.layer setCornerRadius:8];
        [addPicBtn setBackgroundColor:kCOLOR_HEX(@"F4F4F4")];
        //[btn setBackgroundImage:[UIImage imageNamed:@"mask_group"] forState:UIControlStateNormal];
        [addPicBtn setImagePosition:QMUIButtonImagePositionTop];
        [addPicBtn setImage:[UIImage imageNamed:@"kwt_plant_camera"] forState:UIControlStateNormal];
        [addPicBtn setTitle:@"添加图片".rh_localized forState:UIControlStateNormal];
        [addPicBtn.titleLabel setFont:[UIFont systemFontOfSize:12]];
        [addPicBtn setSpacingBetweenImageAndTitle:5];
        [addPicBtn setTitleColor:kCOLOR_HEX(@"AAAAAA") forState:UIControlStateNormal];
        [bgView addSubview:addPicBtn];
        


        kWeakSelf;
        _plantImg = kImageView;
        _plantImg.contentMode = UIViewContentModeScaleAspectFill;
        _plantImg.layer.cornerRadius = 8;
        _plantImg.layer.masksToBounds = YES;
        [bgView addSubview:_plantImg];
        _plantImg.hidden = YES;
        
        [_plantImg mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.bottom.equalTo(addPicBtn);
        }];
        
        QMUIButton *deleteBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
        [deleteBtn setImage:[UIImage imageNamed:@"pic_delete_icon"] forState:UIControlStateNormal];
        [deleteBtn setBackgroundColor:UIColor.clearColor];
        [_footerView addSubview:deleteBtn];
        self.deleteBtnB = deleteBtn;
        self.deleteBtnB.hidden = YES;
        
        [[deleteBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            weakSelf.plantImg.image = nil;
            weakSelf.plantImg.hidden = YES;
            weakSelf.deleteBtnB.hidden = YES;
            weakSelf.uploadImgUrl = nil;
        }];
        
        [deleteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(30, 30));
            make.right.equalTo(addPicBtn).offset(10);
            make.top.equalTo(addPicBtn).offset(-10);
        }];
        
        
        [[addPicBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
            [weakSelf addPicAction];
        }];

        
        [[RACSignal merge:@[textView.rac_textSignal,RACObserve(textView, text)]]subscribeNext:^(NSString*  _Nullable text) {
            [weakSelf.para setObject:text forKey:@"description"];
//            NSLog(@"--->%@",weakSelf.para);
        }];
        
        [lab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(15);
            make.top.mas_offset(15);
            make.right.mas_offset(-15);
            make.height.mas_equalTo(20);
        }];
        
        [textView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(lab);
            make.top.equalTo(lab.mas_bottom).offset(20);
            make.height.offset(110);
                    
        }];
        
        [addPicBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(90, 90));
            make.left.equalTo(lab);
            make.top.equalTo(textView.mas_bottom).offset(20);
        }];
        
        
    }
    return _footerView;
}


#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 3;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 15;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 380;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
   return self.footerView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    RHAddDeviceCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHAddDeviceCell"];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    NSArray *array = @[@"设备名称".rh_localized,@"设备编号".rh_localized,@"安装者".rh_localized];
    NSArray *placeholder_array = @[@"请输入设备名称".rh_localized,@"请输入设备编号".rh_localized,@"请输入安装者".rh_localized];
    [cell.titleLab setText:array[indexPath.row]];
    if([self.dataArr[indexPath.row] length]>0){
        cell.textField.text = self.dataArr[indexPath.row];
    }
    [cell.textField setPlaceholder:placeholder_array[indexPath.row]];
    cell.textField.userInteractionEnabled = NO;
    [cell hideArrowView:(indexPath.row != 0)||self.devModel];
    if(indexPath.row == 0){
        [cell hideArrowView:!self.canSelectDevice];
        [cell setTopBorder];
    }else{
        [cell hideArrowView:YES];
        [cell setMiddleBorder];
    }
    if (indexPath.row == array.count-1) {
        [cell setBottomBorder];
    }
   
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row == 0 && self.canSelectDevice){
        [self deviceList];
    }
    
}

-(void)deviceList
{
    [QMUITips showLoadingInView:self.view];
    NSDictionary *para = @{@"userId":@([PrivateMange share].currentUser.userId),
                           @"pageNum":@(1),
                           @"pageSize":@(10000),
                           @"status":@""
    };
    [RHDeviceModel startGetWithCompletionAPIKey:H_deviceList argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            
            NSMutableArray *arr = [NSMutableArray arrayWithArray:resultModel.data];
            ChoiceDeviceVC *vc = [[ChoiceDeviceVC alloc]init];
            vc.deviceList = arr;
            vc.curModel = self.devModel;
            [[RHWindowTipManage shareWindowTipManage] showWithController:vc];
            [vc showAnimation];
            kWeakSelf;
            vc.choiceResultBlock = ^(RHDeviceModel * _Nonnull model) {
                if(model){
                    weakSelf.devModel = model;
                }
               
               
            };
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
           [self.tableView endHeaderRefresh];
           [self.tableView endFooterRefresh];
    }];

}

#pragma mark ----- 获取上级用户信息
-(void)getSuperUserInfo
{
    [BaseModel startGetWithCompletionAPIKey:H_getSuperAdmins argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        self.superUser = request.responseJSONObject[@"data"][@"email"];
        self.dataArr = @[ValidNullData(self.devModel.deviceName),ValidNullData(self.devModel.deviceId),ValidNullData(self.superUser)];
        [self.tableView reloadData];
         
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}


#pragma mark ----- 开始上报 -----
-(void)checkInfo
{
    if(self.plantImg.image == nil){
        [QMUITips showError:@"请上传图片".rh_localized];
        return;
    }
    if(self.textView.text.length < 10){
        [QMUITips showError:@"描述信息不得少于10个字符".rh_localized];
        return;
    }
    
    
    NSArray *keys = @[@"deviceName",@"deviceId",@"createUser"];
    
    for (int i=0; i<3; i++) {
        RHAddDeviceCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
        if(cell.textField.text.length==0){
            [QMUITips showError:@"请输入完整信息".rh_localized];
            return;
        }
        [self.para setObject:cell.textField.text forKey:keys[i]];
    }
    kWeakSelf;
    //压缩到500K
    [QMUITips showLoading:@"压缩图片...".rh_localized inView:self.view];
    UIImage *image = self.plantImg.image;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        UIImage *compressImg = [self compressImageQuality:image toByte:5000];
        dispatch_async(dispatch_get_main_queue(), ^{
            [QMUITips hideAllTipsInView:weakSelf.view];
            //清除上次上传的
            self.uploadImgUrl = nil;
            //上传图片
            [weakSelf uploadHeadImage:compressImg];
        });
    });

}
-(void)reportFaults{
    [QMUITips showLoading:@"上报设备故障..." inView:self.view];
    [BaseModel startWithCompletionAPIKey:H_warranty argument:self.para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            [QMUITips showSucceed:@"上报成功"];
            if(self.finishBlock){
                self.finishBlock();
            }
            [self.navigationController popViewControllerAnimated:YES];
        }
        
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}

#pragma mark - Action
- (void)addPicAction{
    
    [self norSheetViewWithTitle:@""
                        mess:@""
                            theme:UIColor.blackColor
                            oneTitle:@"拍照".rh_localized
                               twoTitle:@"相册".rh_localized
                                       oneHandler:^{
        [self addPhotoFromCamera];
    }
                                       twoHandler:^{
        [self addPhotoFromAlbum:NO];
        
   }];
}


//从相机拍照
- (void)addPhotoFromCamera{
    if (![ZLPhotoManager haveCameraAuthority]) {
        NSString *message = [NSString stringWithFormat:GetLocalLanguageTextValue(ZLPhotoBrowserNoCameraAuthorityText), kAPPName];
        [SVProgressHUD showInfoWithStatus:message];
        return;
    }
    
    ZLCustomCamera *camera = [[ZLCustomCamera alloc] init];
    camera.allowTakePhoto = YES;
    camera.allowRecordVideo = NO;
    
    kWeakSelf;
    camera.doneBlock = ^(UIImage *image, NSURL *videoUrl) {
        weakSelf.plantImg.image = image;
        weakSelf.deleteBtnB.hidden = NO;
        weakSelf.plantImg.hidden = NO;
    };
    [self showDetailViewController:camera sender:nil];
}

//从相册选择图片
//hasCamera -- 是否附带拍照
- (void)addPhotoFromAlbum:(BOOL)hasCamera{
    ZLPhotoActionSheet *actionSheet = [[ZLPhotoActionSheet alloc] init];
    //设置语言
    actionSheet.configuration.languageType = (ZLLanguageType)[[kUserDefaults objectForKey:@"ZLLanguage"]integerValue];
    //是否升序排列，预览界面不受该参数影响
    actionSheet.configuration.sortAscending = NO;
    //设置相册内部显示拍照按钮
    actionSheet.configuration.allowTakePhotoInLibrary = hasCamera?YES:NO;
    //设置在内部拍照按钮上实时显示相机俘获画面
    actionSheet.configuration.showCaptureImageOnTakePhotoBtn = hasCamera?YES:NO;
    //设置是否允许选择原图
    actionSheet.configuration.allowSelectOriginal = YES;
    //设置是否允许选择视频
    actionSheet.configuration.allowSelectVideo = NO;
    //设置是否允许选择gif
    actionSheet.configuration.allowSelectGif = NO;
    //是否显示选中图片的index 默认YES
    actionSheet.configuration.showSelectedIndex = NO;
    //是否允许编辑
    actionSheet.configuration.allowEditImage = NO;
    
    //预览选择模式下 拍照/相册/取消 的字体颜色 默认 blackColor
    actionSheet.configuration.previewTextColor = kCOLOR_HEX(@"#666666");
    //遮罩层颜色， 默认 blackColor alpha 0.2
    actionSheet.configuration.selectedMaskColor = [[UIColor blackColor] colorWithAlphaComponent: 0.7f];
    // 导航条颜色，默认 rgb(44, 45, 46)
    actionSheet.configuration.navBarColor = [UIColor whiteColor];
    // 导航标题颜色，默认 white
    actionSheet.configuration.navTitleColor = kCOLOR_HEX(@"#222222");
    // 底部工具栏按钮 可交互 状态标题颜色，默认 white
    actionSheet.configuration.bottomBtnsNormalTitleColor = kCOLOR_HEX(@"#222222");
    //底部工具栏按钮 可交互 状态背景颜色，默认rgb(80, 169, 56)
    actionSheet.configuration.bottomBtnsNormalBgColor = kCOLOR_HEX(@"#e9e9e9");
    //底部工具栏按钮 不可交互 状态背景颜色，默认rgb(39, 80, 32)
    //actionSheet.configuration.bottomBtnsDisableBgColor = CDisBtnColor;
    // 底部工具条底色，默认 rgb(44, 45, 46)
    actionSheet.configuration.bottomViewBgColor = kCOLOR_HEX(@"#ffffff");
    //设置照片 cell的圆角弧度
    actionSheet.configuration.cellCornerRadio = 5.0;
    //状态栏样式 默认 UIStatusBarStyleLightContent
    actionSheet.configuration.statusBarStyle = UIStatusBarStyleDefault;
    //设置照片最大预览数
    //actionSheet.configuration.maxPreviewCount = 2;
    //设置照片最大选择数
    actionSheet.configuration.maxSelectCount = 1;
    
    actionSheet.sender = self;

    [actionSheet showPhotoLibrary];
    
    kWeakSelf;
    [actionSheet setSelectImageBlock:^(NSArray<UIImage *> * _Nonnull images, NSArray<PHAsset *> * _Nonnull assets, BOOL isOriginal) {
        
        UIImage *image = images[0];
        weakSelf.plantImg.image = image;
        weakSelf.deleteBtnB.hidden = NO;
        weakSelf.plantImg.hidden = NO;
        //        NSData *imageData = UIImageJPEGRepresentation(image, 1.0f);
        //        NSLog(@"--->图片大小: %ld k", (long)(imageData.length / 1024));
       
    }];

    actionSheet.selectImageRequestErrorBlock = ^(NSArray<PHAsset *> * _Nonnull errorAssets, NSArray<NSNumber *> * _Nonnull errorIndex) {
    };
    
    actionSheet.cancleBlock = ^{
        
       
    };
}

//MARK: NOTE == 普通Sheet弹窗，按钮1和按钮2  主题色
- (void)norSheetViewWithTitle:(NSString *)title
                         mess:(NSString *)mess
                        theme:(UIColor *)themeColor
                     oneTitle:(NSString *)oneTitle
                     twoTitle:(NSString *)twoTitle
                   oneHandler:(dispatch_block_t)oneHandler
                   twoHandler:(dispatch_block_t)twoHandler{
    // 底部按钮
    QMUIAlertAction *action1 = [QMUIAlertAction actionWithTitle: @"取消".rh_localized style:QMUIAlertActionStyleCancel handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        
    }];
    QMUIAlertAction *action2 = [QMUIAlertAction actionWithTitle: oneTitle style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        if (oneHandler) {
            oneHandler();
        }
    }];

    QMUIAlertAction *action3 = [QMUIAlertAction actionWithTitle: twoTitle style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        if (twoHandler) {
            twoHandler();
        }
    }];
    
    QMUIAlertController *alertController = [[QMUIAlertController alloc] initWithTitle: title message: mess preferredStyle:QMUIAlertControllerStyleActionSheet];
    /// sheet内容的圆角，默认值是 13，以保持与系统默认样式一致
    alertController.sheetContentCornerRadius = 6;
    /// sheet按钮高度，默认值是 57，以保持与系统默认样式一致
    alertController.sheetButtonHeight = 58;
    alertController.sheetContentMargin = UIEdgeInsetsMake(10, 12, 10, 12);
    /// sheet的最大宽度，默认值是5.5英寸的屏幕的宽度减去水平的 sheetContentMargin
    //alertController.sheetContentMaximumWidth = 320;
    
    NSMutableDictionary *titleAttributs = [[NSMutableDictionary alloc] initWithDictionary:alertController.sheetTitleAttributes];
    titleAttributs[NSForegroundColorAttributeName] = kCOLOR_HEX(@"#222222");
    titleAttributs[NSFontAttributeName] = [UIFont systemFontOfSize:16];
    titleAttributs[NSParagraphStyleAttributeName] = [NSMutableParagraphStyle qmui_paragraphStyleWithLineHeight: 22 lineBreakMode: NSLineBreakByTruncatingTail textAlignment: NSTextAlignmentCenter];
    
    /// sheet标题样式，默认@{NSForegroundColorAttributeName:UIColorMake(143, 143, 143),NSFontAttributeName:UIFontBoldMake(13),NSParagraphStyleAttributeName:[NSMutableParagraphStyle qmui_paragraphStyleWithLineHeight:0 lineBreakMode:NSLineBreakByTruncatingTail]}
    alertController.sheetTitleAttributes = titleAttributs;
    
    NSMutableDictionary *messageAttributs = [[NSMutableDictionary alloc] initWithDictionary:alertController.sheetMessageAttributes];
     messageAttributs[NSForegroundColorAttributeName] = kCOLOR_HEX(@"#444444");
       messageAttributs[NSFontAttributeName] = [UIFont systemFontOfSize:14];
       messageAttributs[NSParagraphStyleAttributeName] = [NSMutableParagraphStyle qmui_paragraphStyleWithLineHeight: 22 lineBreakMode: NSLineBreakByTruncatingTail];
    /// sheet信息样式，默认@{NSForegroundColorAttributeName:UIColorMake(143, 143, 143),NSFontAttributeName:UIFontMake(13),NSParagraphStyleAttributeName:[NSMutableParagraphStyle qmui_paragraphStyleWithLineHeight:0 lineBreakMode:NSLineBreakByTruncatingTail]}
    alertController.sheetMessageAttributes = messageAttributs;
    
    //alert头部（非按钮部分）背景色
    alertController.alertHeaderBackgroundColor = UIColorWhite;
    //alert按钮背景色
    alertController.alertButtonBackgroundColor = UIColorWhite;
    //alert上分隔线颜色
    alertController.alertSeparatorColor = kCOLOR_HEX(@"#f5f5f5");
    /// alert头部title和message之间的间距
    alertController.alertTitleMessageSpacing = 5;
    
    NSMutableDictionary *buttonAttributes = [[NSMutableDictionary alloc] initWithDictionary:alertController.sheetButtonAttributes];
    buttonAttributes[NSForegroundColorAttributeName] = kCOLOR_HEX(@"#666666");
    buttonAttributes[NSFontAttributeName] = [UIFont systemFontOfSize:16];

    alertController.sheetButtonAttributes = buttonAttributes;
    
    NSMutableDictionary *cancelButtonAttributes = [[NSMutableDictionary alloc] initWithDictionary:alertController.sheetCancelButtonAttributes];
    cancelButtonAttributes[NSForegroundColorAttributeName] = themeColor;
    cancelButtonAttributes[NSFontAttributeName] = [UIFont systemFontOfSize:16];
    alertController.sheetCancelButtonAttributes = cancelButtonAttributes;
    
    [alertController addAction:action1];
    [alertController addAction:action2];
    [alertController addAction:action3];
    [alertController showWithAnimated:YES];
}


#pragma mark -------- 图片上传 ----------------
-(void)uploadHeadImage:(UIImage*)headImg
{
    kWeakSelf;
    [QMUITips showLoading:@"上传图片...".rh_localized inView:self.view];
    [BaseModel startUploadWithCompletionAPIKey:H_uploadImage rgument:@{@"file":@"ios"} image:headImg imageName:nil requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            [QMUITips showSucceed:@"上传成功".rh_localized inView:weakSelf.view];
            //保存图片参数
            weakSelf.uploadImgUrl = request.responseObject[@"url"];
            
            [weakSelf.para setObject:weakSelf.uploadImgUrl forKey:@"image"];
            
            [weakSelf reportFaults];
        }
        
        
        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
           
            
            
        }];
    
}


/// 压缩图片质量
/// - Parameters:
///   - image: 图片
///   - maxLength: 压缩到指定的大小(单位: kb)
- (UIImage *)compressImageQuality:(UIImage *)image toByte:(NSInteger)maxLength {
    
     CGFloat compression = 1;
     NSData *data = UIImageJPEGRepresentation(image, compression);
     while (data.length / 1024 > maxLength && compression > 0) {
         compression -= 0.05;
         // When compression less than a value, this code dose not work
         data = UIImageJPEGRepresentation(image, compression);
         NSLog(@"====>压缩了一次后: %ld k",(long)(data.length / 1024));
     }
     UIImage *resultImage = [UIImage imageWithData:data];
     return resultImage;
}

#pragma mark ------ 扫描二维码

- (void)scanQRC{
    if ([self isCameraAvailable]) {
        [self isCanVisitPhotoAndCameraAuthorization:^(BOOL isOK,NSString *alerStr) {
            if (isOK) {
                NSLog(@"权限OK");
                kWeakSelf;
                CDZQRScanViewController *controller = [[CDZQRScanViewController alloc] init];
                controller.resultCallBack = ^(NSString *macStr) {
                    RHAddDeviceCell *cell = [weakSelf.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
                    cell.textField.text = macStr;
                    
                };
                 RHNavigationController *nav = [[RHNavigationController alloc] initWithRootViewController:controller];
                [nav setModalPresentationStyle:UIModalPresentationOverFullScreen];
                [self presentViewController:nav animated:YES completion:^{
                    
                }];
            }else{
                if (alerStr) {
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:alerStr preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *conform = [UIAlertAction actionWithTitle:@"去设置".rh_localized style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                         if (@available(iOS 10.0, *)) {
                             [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
                             } else {
                             NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                             if ([[UIApplication sharedApplication] canOpenURL:url]) {
                                 [[UIApplication sharedApplication] openURL:url];
                             }
                         }
                    }];
                    
                    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消".rh_localized style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        NSLog(@"点击了取消按钮");
                    }];
                    [alert addAction:cancel];
                    [alert addAction:conform];
                    [self presentViewController:alert animated:YES completion:nil];
                }
            }
        }];
    }

}

// 判断设备是否有摄像头
- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}
- (void)isCanVisitPhotoAndCameraAuthorization:(void(^)(BOOL isOK,NSString *alerStr))result {
    PHAuthorizationStatus photo_status = [PHPhotoLibrary authorizationStatus];
    AVAuthorizationStatus camera_status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (photo_status == PHAuthorizationStatusAuthorized&&camera_status ==AVAuthorizationStatusAuthorized) {
        result(YES,nil);
        return;
    }
    
    if (photo_status == PHAuthorizationStatusRestricted || photo_status == PHAuthorizationStatusDenied||
        camera_status ==AVAuthorizationStatusDenied || camera_status ==AVAuthorizationStatusRestricted) {
        if (photo_status == PHAuthorizationStatusRestricted || photo_status == PHAuthorizationStatusDenied) {
            result(NO,@"Please allow access photos in iPhone's Settings");
        }else{
            result(NO,@"Please allow access camera in iPhone's Settings");
        }
        return ;
    }
    
    if (camera_status == AVAuthorizationStatusNotDetermined) {
        //点击弹框授权
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if(!granted){//不允许
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSLog(@"未开启相机权限,请到设置中开启");
                    result(NO,nil);
                });
            }else{
                if (photo_status == PHAuthorizationStatusNotDetermined) {
                    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                               // 回调是在子线程的
                               NSLog(@"%@",[NSThread currentThread]);
                               dispatch_async(dispatch_get_main_queue(), ^{
                                   if (status != PHAuthorizationStatusAuthorized) {
                                         NSLog(@"未开启相册权限,请到设置中开启");
                                         result(NO,nil);
                                   }else{
                                         result(YES,nil);
                                   }
                               });
                     
                           }];
                }else{
                    dispatch_async(dispatch_get_main_queue(), ^{
                        result(YES,nil);
                    });
                }

            }
        }];
        return;
    }
    
    if (photo_status == PHAuthorizationStatusNotDetermined) {
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                   // 回调是在子线程的
                   NSLog(@"%@",[NSThread currentThread]);
                   dispatch_async(dispatch_get_main_queue(), ^{
                       if (status != PHAuthorizationStatusAuthorized) {
                             NSLog(@"未开启相册权限,请到设置中开启");
                             result(NO,nil);
                       }else{
                             result(YES,nil);
                       }
                   });
               }];
    }
}

@end
